//
//  UIColor+Extension.swift
//  LiveShow
//
//  Created by dai zhong on 2017/4/28.
//  Copyright © 2017年 company.cn. All rights reserved.
//

import UIKit

extension UIColor{

    // MARK: UIColor 转化 RGB值
    public func convetColorToRGB() ->(CGFloat ,CGFloat ,CGFloat){
    
        guard let components = self.cgColor.components else {
            fatalError("请使用RGB方式转换颜色色值");
        }
        return (components[0]*255 ,components[1]*255 ,components[2]*255);
    }
    
    // MARK:rgb
    convenience init(r:CGFloat ,g:CGFloat ,b:CGFloat) {
        self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0);
    }
    
    // MARK:rgba
    convenience init(r:CGFloat ,g:CGFloat ,b:CGFloat ,a:CGFloat = 1.0){
        self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a);
    }
    
    // MARK: randomColor
    class var randomColor:UIColor {
        
        return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)));
    }
    
    // ##ffab12 0xaa8723 #da90fa ffab12
    convenience init?(hexStr:String ,alpha:CGFloat = 1.0) {
        
        guard hexStr.characters.count >= 6 else {
            return nil;
        }
        let hexStrUpper = hexStr.uppercased();
        var targetHexStr:String = hexStrUpper;
        if (hexStrUpper.hasPrefix("##") || hexStrUpper.hasPrefix("0x")) {
            targetHexStr = (hexStrUpper as NSString).substring(from: 2);
        }
        if hexStrUpper.hasPrefix("#") {
            targetHexStr = (hexStrUpper as NSString).substring(from: 1);
        }
        let redStr = (targetHexStr as NSString).substring(with: NSMakeRange(0, 2));
        let greenStr = (targetHexStr as NSString).substring(with: NSMakeRange(2, 2));
        let blueStr = (targetHexStr as NSString).substring(with: NSMakeRange(4, 2));
        
        var red:UInt64 = 0;
        var green:UInt64 = 0;
        var blue:UInt64 = 0;
        Scanner.init(string: redStr).scanHexInt64(&red);
        Scanner.init(string: greenStr).scanHexInt64(&green);
        Scanner.init(string: blueStr).scanHexInt64(&blue);
        
        self.init(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: alpha);
    }
}
